/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.web.controller;

import com.alibaba.druid.util.Base64;
import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.entity.Media;
import com.bifrost.exception.FormatException;
import com.bifrost.common.model.ResultModel;
import com.bifrost.service.MediaService;
import com.bifrost.util.FileUploadUtils;
import com.bifrost.util.HttpContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2017/10/19 12:41
 */
@RestController("apiUploadController")
@RequestMapping("/api/file")
@Api("图片上传接口")
@Slf4j
public class UploadController {
    @Autowired
    MediaService mediaService;

    @ApiOperation(value = "上传图片（可批量上传）")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "file", value = "上传的文件 ", dataType = "file", required = true),
            @ApiImplicitParam(paramType = "form", name = "tag", value = "图片标签", dataType = "String", required = true)
    })
    @PostMapping("/upload")
    public ResultModel upload(@RequestParam("file") MultipartFile files[], @RequestParam("tag") String tag, String title, String altText, HttpServletRequest request) throws IllegalStateException, IOException {
        /*MultipartFile files[] = new MultipartFile[1];
        MockMultipartFile mockMultipartFile    = new MockMultipartFile("temp.png", new FileInputStream(new File("D:\\upload\\file\\temp.png")));
        files[0] = mockMultipartFile;*/
        if (files.length == 0) {
            return ResultModel.error("上传文件数量为0");
        }else{
            List<Media> medias = null;
            try {
                medias = mediaService.upload(files,title,tag,altText);//TODO tag
                if (!CollectionUtils.isEmpty(medias) && medias.size() == files.length) {
                    List resultList = new ArrayList(medias.size());
                    medias.forEach(media -> {
                        Map info = new HashMap(3);
                        info.put("id", media.getMediaId());
                        info.put("url", HttpRequestUtils.getUrl(media.getUrl()));
                        info.put("hash", media.getHash());
                        resultList.add(info);
                    });
                    return  ResultModel.ok().put("result", resultList);
                }
                return ResultModel.error("上传文件失败");
            } catch (FormatException e) {
                return ResultModel.error(e.getErrorMsg());
            }

        }
    }

    @ApiOperation(value = "上传图片（可批量上传）")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "file", value = "上传的文件 ", dataType = "file", required = true),
            @ApiImplicitParam(paramType = "form", name = "tag", value = "图片标签", dataType = "String", required = true)
    })
    @PostMapping("/base64/upload")
    public ResultModel upload(@RequestParam("file") String imgStrs[], @RequestParam("tag") String tag, String title, String altText, HttpServletRequest request) throws IllegalStateException, IOException {

        if (imgStrs.length == 0) {
            return ResultModel.error("上传文件数量为0");
        }else{
            List<MultipartFile> files = new ArrayList<>(imgStrs.length);

            for (String imgStr : imgStrs) {
                // 格式化base64 并校验
                files.add(FileUploadUtils.stringToMultipartFile(imgStr));
            }
            return  upload(files.toArray(new MultipartFile[imgStrs.length]),tag,title,altText,request);
        }
    }


    @GetMapping("/formatImage")
public ResultModel formatALlImages(){
        mediaService.formatImage();
        return  ResultModel.ok();
}

}

